package com.cvo.scrumtoolkit.client.controller;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * This controller can be called for a new Widget. The controller uses a
 * WidgetFactory to delegate creation of the widget
 * 
 * @author Ricardo Cappelle
 * 
 */
public class ControllerImpl implements Controller {
	private static ControllerImpl controller;

	private RootPanel contentPanel;
	
	private ControllerImpl(RootPanel rootPanel) {
			this.contentPanel = rootPanel;
	}

	/**
	 * Singleton controller
	 * @param rootPanel 
	 * 
	 * @return A singleton controller
	 */
	public static ControllerImpl getController(RootPanel rootPanel) {
		if (controller == null) {
			controller = new ControllerImpl(rootPanel);
		}
		return controller;
	}
	
	public static ControllerImpl getController() throws Exception {
		if (controller == null) {
			throw new Exception("Deze methode mag niet aangeroepen worden als er nog geen controller bestaat.");
		}
		return controller;
	}

	/**
	 * Changes a view to another, if token is wrong, default view
	 * 
	 * @return Composite for new view
	 */
	@Override
	public void changeView(View view, String pid, String sprintid) {
			Navigator navigator = Navigator.getNavigator(view, pid, sprintid);
			Widget newview = buildView(navigator);
			this.contentPanel.clear();
			this.contentPanel.add(newview);
	}

	

	/**
	 * Calls the widget factory to build a view for the controller with the
	 * provided data
	 * 
	 * @param data
	 *            The data that must be provided
	 * @return The widget build by the WidgetFactory
	 */
	private Composite buildView(Navigator navigator) {
		return CompositeFactory.getCompositeFactory().createView(navigator);
	}


}
